/*
Copyright (C) 2006-2007 Santostefano Giovanni contact: idmgiovanni@libero.it

This program is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more
details.

You should have received a copy of the
GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/

#include "BlizStretch.h"

/* FUNCTION TEXTURE STRETCHING
 * This function stretch a texture and adapt it to new dimensions
 * defined by the programmer
 */
ITexture* BlizStretchTexture(IrrlichtDevice *device, char* name, ITexture* source, core::dimension2d<s32> newdim)
{

   //get a pointer to the driver
   video::IVideoDriver* driver = device->getVideoDriver();

   //dimension of the original texture
   core::dimension2d<s32> dim=source->getOriginalSize();

   //color format of the original texture
   video::ECOLOR_FORMAT cformat=source->getColorFormat();

   if(cformat!=video::ECF_A8R8G8B8)
      return NULL;

   //calculating scaling factors

   //X factor
   float Xfactor= dim.Width/newdim.Width;
   //int Xfactor = (int)floor(sf); //call to floor is to avoid bugs

   //Y factor
   float Yfactor= dim.Height/newdim.Height;
   //int Yfactor = (int)floor(sf); //call to floor is to avoid bugs

   //creating the new texture
   char *tname=(char*)malloc(sizeof(char)* strlen(name));
   strcpy(tname, name);

   printf("Texture %s Created!\n", tname);

   //populating the texture
   int i=0, j=0;
   SColor *sbuffer=(SColor*)source->lock();
   SColor *dbuffer= new SColor[newdim.Height*newdim.Width];//(SColor*)texture->lock();

   if(!sbuffer)
   {
      printf("ERROR WHILE LOCKING SOURCE TEXTURE\n");
      return NULL;
   }

   for(i=0; i<newdim.Height; i++)
      for(j=0 ; j<newdim.Width; j++)
      {
         //source index
         /*int sXindex=j * Xfactor;
         int sYindex=i * Yfactor;*/
         int sindex=(int)floor((dim.Width*i*Yfactor)+(j*Xfactor));
         int dindex=(i*newdim.Width)+j;
         dbuffer[dindex]=sbuffer[sindex];
         //printf("");
      }

   source->unlock();

   video::IImage* image=driver->createImageFromData(video::ECF_A8R8G8B8,newdim,dbuffer,false);
   video::ITexture* texture=driver->addTexture(tname,image);
   
   return texture;

} 